<template>
  <div class="container">
    <template v-if="loaded">
      <navbar ref="navbar" :title="title" theme="gradient"
              :leftItemIcon="'\ue600'"
              rightItemText="免单教程"
              @rightItemClick="navbarRightClick">
      </navbar>
      <list class="item-list-container" @scroll="onPageScroll">
        <page-refresh v-on:refresh="onXRefresh" v-on:pullingDown="onPullingDown" :refreshing="refreshing"
                      :indicatorScale="indicatorScale"></page-refresh>
        <header>
          <div class="adv-list" ref="top">
            <adv-slider v-if="advSpaceId" :advSpaceId="advSpaceId" border-radius="0"></adv-slider>
          </div>
        </header>
        <header>
          <div class="shopcat-scrollbar" ref="shopcatBar" v-if="showShopcatBar">
            <shopcat-scrollbar v-on:shopcatSelected="shopcatSelected"
                               :shopcatIds="itemSearchParam.catIds"></shopcat-scrollbar>
          </div>
          <filterbar :param="itemSearchParam" :hideEcomPlat="hideEcomPlat"
                     v-on:change="filterbarChange" layout="list" @layout="listLayout"></filterbar>
        </header>
        <template v-if="commissionItemList.length" v-for="(itemList, rowIdx) in commissionItemRowList">
          <item-cell v-bind:key="rowIdx" :layout="commissionItemListLayout" :mark-icon="markIcon"
                     @commissionItemClick="commissionItemClick" :itemList="itemList"></item-cell>
        </template>
        <cell>
          <page-notice msg="抱歉，什么都木有找到～" :icon="sorryIcon" v-if="!commissionItemList.length && !hasNext"></page-notice>
        </cell>
        <page-loading-more v-on:loadingMore="onLoadingMore" :loadingMore="loadingMore"
                           :shown="hasNext"></page-loading-more>
      </list>
      <page-scrolltop :shown="pageScrollTopShown" @click="gotoTop"></page-scrolltop>
      <wxc-loading :show="loadingShow"></wxc-loading>
      <wxc-mask height="900"
                width="700"
                duration="200"
                mask-bg-color="#FFFFFF"
                border-radius="20"
                :has-animation="true"
                :has-overlay="true"
                :show-close="true"
                :show="maskShow"
                @wxcMaskSetHidden="maskSetHidden">
        <web :src="helpUrl" style="width:700; height: 900; border-radius: 20; overflow: hidden;" v-if="maskShow"></web>
      </wxc-mask>
    </template>
    <page-loading :loaded="loaded"></page-loading>
  </div>
</template>
<style lang="scss">
  @import "./sass/var";
  @import "./sass/mixin";
  @import "./sass/utilities";
  @import "./sass/icon";
  @import "./sass/buttons";

  .container {
    background-color: $body-bg;
    transition: transform .3s linear;
    position: relative;
  }

  .shopcat-scrollbar {
    background-color: #ffffff
  }

  .adv-list {
  }

</style>
<script>

import {WxcLoading, WxcMask} from 'weex-ui'
let api = require('./include/api')
let Deferred = require('Deferred')
let urlPath = require('./include/url-path')
let navigator = require('./include/xnavigator')
let queryparser = require('./include/queryparser')
let grouping = require('./include/grouping')

let config = require('./include/app-config')
const DEFAULT_ITEM_SEARCH_PARAM = {
  page: 1,
  sort: 'NONE',
  keywords: '',
  ecomPlat: '',
  startPrice: '',
  endPrice: '',
  channelIds: '',
  catIds: '',
  recommend: '',
  freeShipment: false,
  freeChargeActivityId: 0
}
module.exports = {
  mixins: [
    require('./mixin/page-refresh'),
    require('./mixin/page-loading-more'),
    require('./mixin/page-loading'),
    require('./mixin/page-scrolltop')
  ],
  components: {
    'shopcat-scrollbar': require('./components/shopcat-scrollbar.vue'),
    'page-notice': require('./components/page-notice.vue'),
    'searchbar': require('./components/searchbar.vue'),
    'filterbar': require('./components/filterbar.vue'),
    'navbar': require('./components/navbar.vue'),
    WxcLoading,
    WxcMask,
    'item-cell': require('./components/commission-item-cell.vue'),
    'adv-slider': require('./components/adv-slider.vue')
  },
  props: {

  },
  data () {
    return {
      commissionItemList: [],
      commissionItemRowList: [],
      refreshing: false,
      refreshIndicatorScale: 0.2,
      hasNext: true,
      shopcatId: '',
      sorryIcon: urlPath.assets('images/aiya.png'),
      topbarHide: false,
      itemSearchParam: Object.assign({}, DEFAULT_ITEM_SEARCH_PARAM),
      showShopcatBar: true,
      loadingShow: false,
      iosShow: false,
      loaded: false,
      commissionItemListLayout: 'list',
      hideEcomPlat: false,
      id: 0,
      title: '免单',
      markIcon: '',
      advSpaceId: null,
      advList: [],
      materialConfig: {},
      helpUrl: '',
      maskShow: false
    }
  },
  created () {
    config.bindConfig(this)
    let params = queryparser(weex.config.bundleUrl)
    if (params.keywords) {
      params.keywords = decodeURIComponent(params.keywords)
    }
    if (params.ecomPlat) {
      this.hideEcomPlat = true
    }
    // 默认搜索本站点
    if (params.title) {
      this.title = decodeURIComponent(params.title)
      delete params.title
    }
    this.id = params.id
    this.advSpaceId = params.advSpaceId
    Object.assign(DEFAULT_ITEM_SEARCH_PARAM, params)
    this.itemSearchParam = Object.assign({}, DEFAULT_ITEM_SEARCH_PARAM)
    if (params.showShopcat === 'false' || params.showShopcat === '0') {
      this.showShopcatBar = false
    }
    Deferred.when(this.loadData()).always(() => {
      this.loaded = true
      this.maskShow = true
    })
  },
  methods: {
    loadData () {
      return api.page.freeChargeActivity.data({
        id: this.id
      }).done(rs => {
        let data = rs.data
        this.title = data.freeChargeActivityName
        this.helpUrl = data.helpUrl
        this.markIcon = data.markIcon
        for (var key in data.materialConfig) {
          if (data.materialConfig[key] == null) {
            delete data.materialConfig[key]
          }
        }
        Object.assign(DEFAULT_ITEM_SEARCH_PARAM, data.materialConfig)
        Object.assign(this.itemSearchParam, data.materialConfig)
        this.searchItem()
      })
    },
    loadAdvSpace () {
      if (this.advSpaceId) {
        return api.advSpaceId.advList({id: this.advSpaceId}).done(rs => {
          this.advList = rs.data
        })
      }
    },
    resetSearchParam () {
      Object.assign(this.itemSearchParam, DEFAULT_ITEM_SEARCH_PARAM)
      this.hasNext = true
    },
    searchItem (append, callback) {
      return api.search.commissionItem(this.itemSearchParam).done((rs) => {
        if (append) {
          this.commissionItemList = this.commissionItemList.concat(rs.data.results)
        } else {
          this.commissionItemList = rs.data.results
        }
        this.commissionItemRowList = grouping(this.commissionItemList, 2)
        let paging = rs.data
        this.hasNext = paging.hasNext
      }).always(() => {
        callback && callback()
      })
    },
    searchBarSearch (kw) {
      DEFAULT_ITEM_SEARCH_PARAM.keywords = kw
      this.resetSearchParam()
      this.loadingShow = true
      this.itemSearchParam.keywords = kw
      this.searchItem().always(() => {
        this.loadingShow = false
      })
    },
    listLayout (layout) {
      this.commissionItemListLayout = layout
    },
    onXRefresh (event) {
      this.itemSearchParam.page = 1
      this.onRefresh(event, Deferred.when(this.loadData(), this.searchItem().always(() => {
      })))
    },
    onLoadingMore (event) {
      this.loadingMore = true
      this.itemSearchParam.page = this.itemSearchParam.page + 1
      this.searchItem(true, () => {
        this.loadingMore = false
      })
    },
    gotoTop () {
      let dom = weex.requireModule('dom')
      dom.scrollToElement(this.$refs.top)
    },
    shopcatSelected (shopcat) {
      this.loadingShow = true
      this.itemSearchParam.catIds = shopcat.id
      this.searchItem(false, rs => {

      }).always(() => {
        this.loadingShow = false
      })
    },
    onPageScroll (event) {
      this.onPageScrollForScrollTop(event)
    },
    filterbarChange () {
      this.loadingShow = true
      this.searchItem(false, rs => {
        this.loadingShow = false
      })
    },
    commissionItemClick (item) {
      navigator.push('commission-item.js?id=' + item.id + '&freeChargeActivityId=' + this.id)
    },
    navbarRightClick () {
      navigator.push({
        url: 'webpage.js?url=' + encodeURIComponent(this.helpUrl) + '&title=' + encodeURIComponent(this.title)
      })
    },
    maskSetHidden () {
      this.maskShow = false
    }
  }
}
</script>
